<template>
  <div class="home-page">
    <div class="home-page-1">
      <div class="user-info-welcome">
        <img alt="" class="user-pic" src="/src/assets/images/profile.jpg">
        <div class="user-text">
          <div class="hello">你好，{{ userInfo.nickName }}，</div>
          <div class="hello">
            今天是{{ $parseTime(new Date(), '{y}-{m}-{d}') }}<span class="ml10">星期{{
              "日一二三四五六".charAt(new Date().getDay())
            }}</span>
            ，欢迎使用,祝您心情美好，开心每一天。
          </div>
        </div>
      </div>
      <div class="user-info-message">
        <div>
          <p class="message-number">{{ totalInfo.deptPendingPatient }}人</p>
          <p class="message-title">科室待诊人(今日)</p>
        </div>
        <div>
          <p class="message-number">{{ totalInfo.deptAlreadyPatient }}人</p>
          <p class="message-title">科室已诊(今日)</p>
        </div>
        <div>
          <p class="message-number">{{ totalInfo.pendingPatient }}人</p>
          <p class="message-title">待诊(今日)</p>
        </div>
        <div>
          <p class="message-number">{{ totalInfo.alreadyPatient }}人</p>
          <p class="message-title">已诊(今日)</p>
        </div>
      </div>
    </div>
    <div class="home-page-2">
      <div class="tag-list-item">
        <div class="tag-list-img" style="background-color: #4caff3">已开<br>处方</div>
        <div class="tag-list-text">{{ applyCountMap.prescriptioncount }}</div>
      </div>
      <div class="tag-list-item">
        <div class="tag-list-img" style="background-color: #02886e">已开<br>检查</div>
        <div class="tag-list-text">{{ applyCountMap.examcount }}</div>
      </div>
      <div class="tag-list-item">
        <div class="tag-list-img" style="background-color: #94026b">已开<br>检验</div>
        <div class="tag-list-text">{{ applyCountMap.labcount }}</div>
      </div>
      <div class="tag-list-item">
        <div class="tag-list-img" style="background-color: #340085">已开<br>治疗</div>
        <div class="tag-list-text">{{ applyCountMap.treatcount }}</div>
      </div>
      <div class="tag-list-item">
        <div class="tag-list-img" style="background-color: #a45502;font-size: 12px">入院通<br>&nbsp;知单</div>
        <div class="tag-list-text">{{ applyCountMap.noticecount }}</div>
      </div>
      <div class="tag-list-item">
        <div class="tag-list-img" style="background-color: #1e6400">今日<br>入院</div>
        <div class="tag-list-text">{{ applyCountMap.inflagok }}</div>
      </div>
      <div class="tag-list-item">
        <div class="tag-list-img" style="background-color: #a20000">今日<br>出院</div>
        <div class="tag-list-text">{{ applyCountMap.inflagno }}</div>
      </div>
      <div class="tag-list-item">
        <div class="tag-list-img" style="background-color: #55006c">...</div>
        <div class="tag-list-text"></div>
      </div>
    </div>
    <div class="home-page-3">
      <el-card class="card-header">
        <template #header>
          <div>
            <span>快捷导航栏<el-button class="ml20" link style="color: rgb(31 79 226);float: right;"
                                       @click="shortcutNavigationClick">
                    添加快捷导航
                </el-button>
            </span>
          </div>
        </template>
        <div v-if="fastMenu.length > 0" style="height: 100%;overflow-y: auto;">
          <el-row>
            <div v-for="(item, index) in fastMenu" :key="index">
              <el-tooltip :content="item.title" class="item" effect="dark" placement="top">
                <div :key="index" class="ckeck-btn fast-item" @click="onChooseItem(item)">
                  <el-card style="height: 100%;">
                    <svg-icon :icon-class="item.icon" class="svg-icon-nav"/>
                    <i :style="{ color: getMenuColor(index) }" class="iconfont"></i>
                    <span class="span">{{ item.title }}</span>
                  </el-card>
                </div>
              </el-tooltip>
            </div>
          </el-row>
        </div>
        <div v-else>暂无数据</div>
      </el-card>
    </div>
    <div id="home-page-4" class="home-page-4"></div>
    <div id="home-page-5" class="home-page-5"></div>
    <div id="home-page-6" class="home-page-6"></div>
    <div class="home-page-7">
      <div class="department-table">
        <div class="home-page-6-title">门诊患者列表(当天)</div>
        <el-table
          v-adaptive="60"
          :border="true"
          :data="outpatientRecordsList"
          :header-cell-style="$headerCellStyle"
          :stripe="true"
          highlight-current-row
        >
          <el-table-column :align="'left'"
                           :header-align="'center'" fixed="left" label="患者信息" prop="name" width="160">
            <template #default="scope">
              <span class="mr5" style="color: #0032e1">{{ scope.row.name }}</span>
              <span class="mr5">
                            <svg-icon :icon-class="dictStore.getMateDictInfo(
                                dictDataMap['sys_user_sex'],
                                scope.row.sex
                            ).dictValue === '1'
                                ? 'man'
                                : 'woman'
                                " style="margin-left: 10px"/>
                        </span>
              {{ scope.row.ageAll }}
            </template>
          </el-table-column>
          <el-table-column :align="'center'" label="就诊日期" prop="visitDate" width="100">
            <template #default="scope">
              <span>{{ $parseTime(scope.row.visitDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column
            :align="'center'"
            :show-overflow-tooltip="true"
            label="是否填写传染病记录"
            prop="isCommunicableDisease"
            width="80"
          >
            <template #default="scope">
              <dict-data-tag
                :options="dictDataMap['sys_yes_no']"
                :value="scope.row.isCommunicableDisease"
              />
            </template>
          </el-table-column>
          <el-table-column
            :align="'center'"
            :show-overflow-tooltip="true"
            label="就诊科室"
            prop="deptName"
            width="100"
          />
          <el-table-column
            :align="'center'"
            :show-overflow-tooltip="true"
            label="接诊医生"
            prop="doctorName"
            width="80"
          />
          <el-table-column
            :align="'center'"
            :show-overflow-tooltip="true"
            label="门诊号"
            prop="clinicNo"
            width="140">
            <template #default="scope">
              <span class="ys-css">{{ scope.row.clinicNo }}</span>
            </template>
          </el-table-column>
          <el-table-column
            :align="'center'"
            :show-overflow-tooltip="true"
            label="身份"
            prop="identity"
            width="80">
            <template #default="scope">
              <dict-data-tag
                :options="dictDataMap['profession_dict']"
                :value="scope.row.identity"
              />
            </template>
          </el-table-column>
          <el-table-column
            :align="'center'"
            :show-overflow-tooltip="true"
            label="是否初诊"
            prop="firstVisitIndicator"
            width="50"
          >
            <template #default="scope">
              <dict-data-tag
                :options="dictDataMap['sys_yes_no']"
                :value="scope.row.firstVisitIndicator"
              />
            </template>
          </el-table-column>
          <el-table-column
            :align="'center'"
            :show-overflow-tooltip="true"
            label="是否住院"
            prop="isHospital"
            width="50"
          >
            <template #default="scope">
              <dict-data-tag
                :options="dictDataMap['sys_yes_no']"
                :value="scope.row.isHospital"
              />
            </template>
          </el-table-column>
          <el-table-column
            :align="'center'"
            :show-overflow-tooltip="true"
            label="监护人"
            prop="guardianName"
            width="80"
          />
          <el-table-column
            :align="'center'"
            :show-overflow-tooltip="true"
            label="监护人电话"
            prop="guardianPhone"
            width="110"/>
          <el-table-column
            :align="'left'"
            :header-align="'center'"
            :show-overflow-tooltip="true"
            label="发病日期"
            prop="fabingriqi"
            width="100"
          />
          <el-table-column
            :align="'left'"
            :header-align="'center'"
            :show-overflow-tooltip="true"
            label="诊断"
            prop="diagnosisStr"
            width="180"
          />
          <el-table-column
            :align="'left'"
            :header-align="'center'"
            :show-overflow-tooltip="true"
            label="主诉"
            prop="zhusu"
          />
          <el-table-column
            :align="'center'"
            :show-overflow-tooltip="true"
            label="血压(mmHg)"
            prop="xueya"
            width="100">
            <template #default="scope">
              {{ scope.row.systolicPressure }}/{{ scope.row.diastolicPressure }}
            </template>
          </el-table-column>
          <el-table-column
            :align="'center'"
            :show-overflow-tooltip="true"
            label="空腹血糖(mmol/L)"
            prop="fbg"
            width="100">
            <template #default="scope">
              {{ scope.row.fbg || '/' }}
            </template>
          </el-table-column>
          <el-table-column
            :align="'left'"
            :header-align="'center'"
            :show-overflow-tooltip="true"
            label="处理意见"
            prop="dispose"
            width="110"
          />
          <el-table-column
            :align="'center'"
            :show-overflow-tooltip="true"
            label="身份证号"
            prop="idNo"
            width="150"
          />
          <el-table-column
            :align="'center'"
            :show-overflow-tooltip="true"
            label="联系电话"
            prop="phone"
            width="130"
          />
          <el-table-column
            :align="'left'"
            :header-align="'center'"
            :show-overflow-tooltip="true"
            label="住址"
            prop="address"
            width="260"
          />
        </el-table>
        <pagination
          v-model:limit="queryParams.pageSize"
          v-model:page="queryParams.pageNum"
          :total="total"
          @pagination="getOutpatientRecordsListFun"
        />
      </div>
    </div>
    <div class="home-page-8">
      <div class="department-table">
        <div class="home-page-6-title">当前住院患者</div>
        <el-table v-adaptive="60" :border="true" :data="patientInfoList"
                  :header-cell-style="$headerCellStyle"
                  :stripe="true">
          <el-table-column :align="'center'" label="房号" prop="roomNo" width="80"/>
          <el-table-column :align="'center'" label="床号" prop="bedNo" width="80"/>
          <el-table-column :align="'left'"
                           :header-align="'center'" label="患者信息" prop="name" width="140">
            <template #default="scope">
              {{ scope.row.name }}
              <span style="margin-left: -10px">
                            <svg-icon :icon-class="dictStore.getMateDictInfo(
                                dictDataMap['sys_user_sex'],
                                scope.row.sex
                            ).dictValue === '1'
                                ? 'man'
                                : 'woman'
                                " style="margin-left: 10px"/>
                        </span>
              {{ scope.row.age }} 岁{{ scope.row.ageMonth }} 月
              <!-- {{ scope.row.ageDay }}天 -->
            </template>
          </el-table-column>
          <el-table-column :align="'center'" label="住院号" prop="hospitalNo" width="130">
            <template #default="scope">
              <span class="ys-css">{{ scope.row.hospitalNo }}</span>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" label="入院时间" prop="admissionTime" width="180">
            <template #default="scope">
              <span>{{ $parseTime(scope.row.admissionTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" label="预交金" prop="patPrepaymentSum" width="120">
            <template #default="scope">
                    <span class="ys-css">{{
                        scope.row.patPrepaymentSum
                          ? scope.row.patPrepaymentSum : 0.00
                      }}</span>元
            </template>
          </el-table-column>
          <el-table-column :align="'center'" label="产生费用" prop="costs" width="120">
            <template #default="scope">
                    <span class="ys-css">{{
                        scope.row.costs
                          ? scope.row.costs : 0.00
                      }}</span>元
            </template>
          </el-table-column>
          <el-table-column :align="'center'" label="预交金余额" prop="patPrepaymentSumBalance" width="120">
            <template #default="scope">
                    <span class="ret-ys-css">{{
                        (Number(scope.row.patPrepaymentSum) - Number(scope.row.costs)).toFixed(2)
                      }}</span>元
            </template>
          </el-table-column>
          <el-table-column :align="'center'" label="管床医生" prop="doctorInChargeName" width="120"/>
          <el-table-column :align="'center'" label="责任护士" prop="dutyNurseName" width="120"/>
          <el-table-column :align="'center'" label="病情状态" prop="situationType" width="80">
            <template #default="scope">
              <dict-data-tag :options="dictDataMap['disease_dict']" :value="scope.row.situationType"/>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" label="护理等级" prop="nursingClassName" width="120"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="诊断"
                           prop="diagnosis"/>
          <el-table-column :align="'center'" label="患者所在科室" prop="deptStayedName" width="100"/>
          <el-table-column :align="'center'" label="患者所在病区" prop="wardCodeName" width="100"/>
        </el-table>
        <pagination
          v-model:limit="patVisitQueryParams.pageSize"
          v-model:page="patVisitQueryParams.pageNum"
          :total="patVisitTotal"
          @pagination="getPatVisitList"
        />
      </div>
    </div>
    <!-- 快捷导航栏配置 -->
    <shortcut-navigation ref="shortcutNavigation" @refreshParent="refreshParent"/>
  </div>
</template>

<script lang="ts" setup>
import {getDoctorDataCollect, getShortcutNavigation} from "@/api/welcomeApi"
import {getOutpatientRecordsList} from "@/api/patient/clinicMaster.ts"
import ShortcutNavigation from "@/components/welcome/ShortcutNavigation.vue"
import {useDictStoreHook} from "@/store/modules/dict.ts";
import {useRoute, useRouter} from "vue-router";
import * as echarts from 'echarts';
//
// import userImg from '@/assets/user.png';
// import fenxiImg from '@/assets/fenxi.png';
// import shangpinImg from '@/assets/shangpin.png';
// import dingdanImg from '@/assets/dingdan.png';
// import piaojuImg from '@/assets/piaoju.png';
// import messageImg from '@/assets/message.png';
// import tagImg from '@/assets/tag.png';
// import peizhiImg from '@/assets/peizhi.png';
import {useUserStoreHook} from "@/store/modules/user.ts";
import eventBus from "@/utils/eventBus.ts";
import {inHospitalPatientList} from "@/api/hospitalization/patVisit.ts";

const useUserStore = useUserStoreHook();
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo;

const router = useRouter()
// 路由
const route = useRoute();
const dictStore = useDictStoreHook();
const dictDataMap = ref(
  dictStore.isTypeGetData(
    "user_post_dict", 'sys_yes_no', 'profession_dict', 'sys_user_sex',
  )
);
const {proxy} = getCurrentInstance() as any;
const date = proxy.$parseTime(new Date(), "{y}-{m}-{d} ");
const dateRange = ref([date + "00:00:00", date + "23:59:59"]);


const userPostArray = ref([])
type totalInfoType = {
  // 已诊人数
  alreadyPatient: number,
  // 未诊人数
  pendingPatient: number,
  // 退号人数
  refundPatient: number,
  // 科室未诊人数
  deptPendingPatient: number,
  // 科室已诊人数
  deptAlreadyPatient: number,
  // 科室退号人数
  deptRefundPatient: number
}
const userId = ref(userInfo.userId)
const dateValue = reactive(new Date())
const nickName = ref(userInfo.nickName)
//首页患者柱状图返回
const patientBarChartVos = ref<any>([]);
//首页患者费用折线图返回
const zheXianInfo = ref<any>([]);
//首页患者费用折线图X轴数据
const xAxisData = ref<any>([]);
// 首页住院费用柱状图数据
const inpBillDetailVos = ref<any>([]);
const totalInfo: any = ref<totalInfoType>({
  // 已诊人数
  alreadyPatient: 0,
  // 未诊人数
  pendingPatient: 0,
  // 退号人数
  refundPatient: 0,
  // 科室未诊人数
  deptPendingPatient: 0,
  // 科室已诊人数
  deptAlreadyPatient: 0,
  // 科室退号人数
  deptRefundPatient: 0
})

// 查询首页患者数据(按检查、检验、治疗、处方分组查开单数量)
const applyCountMap: any = ref({
  // 检查
  examcount: 0,
  // 检验
  labcount: 0,
  // 处方分组查开单数量
  prescriptioncount: 0,
  // 治疗
  treatcount: 0,
  // 入院通知单
  noticecount: 0,
  // 在院
  inflagok: 0,
  // 出院
  inflagno: 0,
})
const currentSelectDept = ref("")
const shortcutNavigation = ref()
const fastMenu = ref<any>([{}])

const colorList = reactive(["#5584fd", "#3470ff", "#ff8801", "#00d6b9", "#7e3bf3"])

const onChooseItem = (item: { path: any; }) => {
  router.push({path: item.path});
}
const getMenuColor = (index) => {
  return colorList[index % 4];
}
const refreshParent = () => {
  getList()
}

//  柱状图
const initZhuZhuang = () => {
  var chartDomZhuZhuang = document.getElementById('home-page-4');
  var myChartZhuZhuang = echarts.init(chartDomZhuZhuang);
  var option;

  option = {
    title: {
      text: '就诊信息统计(人次)',
      color: '#333338',
      left: 'left'
    },
    legend: {
      data: ['待诊', '已诊', '未诊', '退号'],  // 保持4个图例
      top: 20,
    },
    dataset: {
      source: patientBarChartVos.value
    },
    grid: {
      top: '25%',
      bottom: '10%',
      left: '7%',
      right: '2%'
    },
    xAxis: {
      type: 'category',  // X轴为4个类别
      axisLabel: {
        color: '#CBCCCD'
      },
      // 新增：X 轴内部分割线（网格线）配置
      splitLine: {
        show: true, // 显示分割线
        lineStyle: {
          color: '#f0f0f0', // 分割线颜色（浅灰色，与背景区分）
          width: 1,// 分割线宽度
          type: 'solid' // 显式设置实线（默认可能为虚线）
        }
      }
    },
    yAxis: {
      type: 'value',
      axisTick: {
        show: false
      },
      axisLabel: {
        color: '#CBCCCD',
        formatter: '{value} 人'
      },
      // 新增：显示 Y 轴轴线（主线条）
      axisLine: {
        show: true, // 强制显示轴线
        lineStyle: {
          color: '#e5e5e5', // 轴线颜色（浅灰色，可选）
          width: 1 // 轴线宽度（可选）
        }
      },
      // 添加以下配置确保Y轴只显示正整数
      min: 0,          // 最小值为0（正整数起点）
      interval: 1,     // 刻度间隔为1（确保只显示整数）
      splitNumber: 5   // 适当设置分割段数，避免刻度过于密集
    },
    series: [
      {
        name: '待诊',  // 待诊系列
        type: 'bar',
        barGap: '80%',  // 增加同类别下系列间距
        encode: {y: 1},  // 使用数据源第2列数据
        itemStyle: {
          borderRadius: [3, 3, 0, 0],
          color: '#4e64f6'  // 蓝色
        },
        label: {
          show: true,
          position: 'top',
          color: '#4e64f6',
          formatter: function (params: any) {
            if (params.seriesName === '待诊') {
              return params.value[1];
            }
          }
        }
      },
      {
        name: '已诊',  // 已诊系列
        type: 'bar',
        barGap: '80%',  // 增加同类别下系列间距
        encode: {y: 2},  // 使用数据源第3列数据
        itemStyle: {
          borderRadius: [3, 3, 0, 0],
          color: '#349D5f'  // 绿色
        },
        label: {
          show: true,
          position: 'top',
          color: '#349D5f',
          formatter: function (params: any) {
            if (params.seriesName === '已诊') {
              return params.value[2];
            }
          }
        }
      },
      {
        name: '未诊',  // 未诊系列
        type: 'bar',
        barGap: '80%',  // 增加同类别下系列间距
        encode: {y: 3},  // 使用数据源第4列数据
        itemStyle: {
          borderRadius: [3, 3, 0, 0],
          color: '#ff8801'  // 橙色
        },
        label: {
          show: true,
          position: 'top',
          color: '#ff8801',
          formatter: function (params: any) {
            if (params.seriesName === '未诊') {
              return params.value[3];
            }
          }
        }
      },
      {
        name: '退号',  // 退号系列
        type: 'bar',
        barGap: '80%',  // 增加同类别下系列间距
        encode: {y: 4},  // 使用数据源第5列数据
        itemStyle: {
          borderRadius: [3, 3, 0, 0],
          color: '#f56c6c'  // 红色
        },
        label: {
          show: true,
          position: 'top',
          color: '#f56c6c',
          formatter: function (params: any) {
            if (params.seriesName === '退号') {
              return params.value[4];
            }
          }
        }
      }
    ]
  };

  option && myChartZhuZhuang.setOption(option);
}

// 折线图
const initZheXian = () => {
  var chartDomZheXian = document.getElementById('home-page-5');
  var myChartZheXian = echarts.init(chartDomZheXian);
  var optionZheXian;

  optionZheXian = {
    title: {
      text: '门诊费用信息(元)'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      top: 20,
    },
    grid: {
      top: '30%',
      left: '0',
      right: '5%',
      bottom: '3%',
      containLabel: true
    },
    toolbox: {
      show: false,
      feature: {
        saveAsImage: {}
      }
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      axisTick: {
        show: false // 隐藏刻度线
      },
      data: xAxisData.value,
      // 新增：X 轴内部分割线（网格线）配置
      splitLine: {
        show: true, // 显示分割线
        lineStyle: {
          color: '#f0f0f0', // 分割线颜色（浅灰色，与背景区分）
          width: 1,// 分割线宽度
          type: 'solid' // 显式设置实线（默认可能为虚线）
        }
      }
    },
    yAxis: {
      type: 'value',
      axisTick: {
        show: true // 隐藏刻度线
      },
      // 新增：显示 Y 轴轴线（主线条）
      axisLine: {
        show: true, // 强制显示轴线
        lineStyle: {
          color: '#e5e5e5', // 轴线颜色（浅灰色，可选）
          width: 1 // 轴线宽度（可选）
        }
      },
    },
    series: zheXianInfo.value
  };

  optionZheXian && myChartZheXian.setOption(optionZheXian);

}

//  住院柱状图 - 费用统计
const initZhuYuanZhuZhuang = () => {
  var chartDomZhuZhuang = document.getElementById('home-page-6');
  var myChartZhuZhuang = echarts.init(chartDomZhuZhuang);
  var option;

  // 定义不同颜色（可根据需要扩展）
  const colors = ['#5584fd', '#3470ff', '#ff8801', '#00d6b9', '#7e3bf3', '#ff5252', '#2196f3'];

  // 住院费用数据（实际应用中可能从API获取）
  const chargeData = inpBillDetailVos.value;

  // 提取x轴和y轴数据
  const xAxisData = chargeData.slice(1).map(item => item[0]);
  const seriesData = chargeData.slice(1).map((item, index) => ({
    name: item[0],
    value: item[1],
    itemStyle: {color: colors[index % colors.length]}
  }));

  option = {
    title: {
      text: '住院费用统计(元)',
      color: '#333338',
      left: 'left'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: '{b}: {c} 元'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: xAxisData,
        axisTick: {
          alignWithLabel: true
        },
        axisLabel: {
          color: '#CBCCCD'
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '费用 (元)',
        axisTick: {
          show: false
        },
        axisLabel: {
          color: '#CBCCCD',
          formatter: '{value} 元'
        },
        axisLine: {
          show: true,
          lineStyle: {
            color: '#e5e5e5',
            width: 1
          }
        },
        min: 0
      }
    ],
    series: [
      {
        name: '费用',
        type: 'bar',
        barWidth: '60%',
        data: seriesData,
        label: {
          show: true,
          position: 'top',
          formatter: '{c} 元'
        }
      }
    ]
  };

  option && myChartZhuZhuang.setOption(option);

  // 监听窗口大小变化，重新调整图表大小
  window.addEventListener('resize', () => {
    myChartZhuZhuang.resize();
  });
}
// 门诊患者列表
const outpatientRecordsList = ref<any>([]);
// 当前住院患者列表
const patientInfoList = ref<any>([]);
const total = ref(0);
const queryParams = ref<any>({
  pageNum: 1,
  pageSize: 30,
  deptId: currentSelectDept.value,
  doctorId: '',
  name: '',
  isHospital: '',
  isEmergency: '',
  orgId: userInfo.orgId,
  visitDate: proxy.$parseTime(new Date(), "{y}-{m}-{d}")
})

const patVisitQueryParams = ref<any>({
  pageNum: 1,
  pageSize: 30,
  orgId: userInfo.orgId,
  inFlag: "1",
  // 出院时间是否为空 0是 1否
  isDischargeTime: 0,
  doctorInCharge: userInfo.userId
})
const patVisitTotal = ref(0)

/**
 * 查询门诊患者列表
 */
function getOutpatientRecordsListFun() {
  if (currentSelectDept.value && outpatientRecordsList.value.length === 0) {
    queryParams.value.deptId = currentSelectDept.value
    getOutpatientRecordsList(proxy.$addDateRange(queryParams.value, dateRange.value)).then((res: resType) => {
      outpatientRecordsList.value = res.rows
      total.value = res.total as number
    })
  }
}

/**
 * 查询当前住院患者列表
 */
function getPatVisitList() {
  inHospitalPatientList(patVisitQueryParams.value).then((res: resType) => {
    patientInfoList.value = res.rows
    patientInfoList.value.forEach((item: any) => {
      let thisPatPrepaymentSum: number = 0
      if (item.patPrepaymentVos) {
        item.patPrepaymentVos.forEach((patPrepayment: any) => {
          thisPatPrepaymentSum += Number(patPrepayment.amountOfMoney)
        })
      }
      item.patPrepaymentSum = thisPatPrepaymentSum.toFixed(2)
      let thisCosts: number = 0
      if (item.InpBillDetailVos) {
        item.InpBillDetailVos.forEach((patPrepayment: any) => {
          thisCosts += Number(patPrepayment.costs)
        })
      }
      item.costs = thisCosts.toFixed(2)
    })
    patVisitTotal.value = res.total as number
  })
}


// 根据进度返回进度条颜色
const getProgressColor = (percentage) => {
  if (percentage >= 100) {
    return '#67C23A';
  } else if (percentage >= 70) {
    return '#409EFF';
  } else if (percentage >= 30) {
    return '#E6A23C';
  } else {
    return '#F56C6C';
  }
};

/**
 * 查询医生数据
 */
function getDoctorDataCollectFun() {
  if (currentSelectDept.value) {
    const query = {
      orgId: userInfo.orgId,
      visitDate: proxy.$parseTime(new Date(), "{y}-{m}-{d}")
    }
    getDoctorDataCollect(proxy.$addDateRange(query, dateRange.value)).then(res => {
      const data = res.data
      if (data) {
        patientBarChartVos.value = data.patientBarChartVos
        // 1. 获取原始数据
        const originalData = data.patientBarChartVos || []

        // 2. 转换数据格式
        const transformedData = [
          ['category', '待诊', '已诊', '未诊', '退号'] // 头部标题行
        ]

        // 3. 映射原始数据到目标格式
        originalData.forEach(item => {
          transformedData.push([
            item.visitDate, // X轴分类（日期）
            item.pendingDiagnosis, // 待诊人数
            item.okDiagnosis,      // 已诊人数
            item.notDiagnosis,     // 未诊人数
            item.returnNumber      // 退号人数
          ])
        })
        patientBarChartVos.value = transformedData
        initZhuZhuang()
        // 折线图原始数据
        const zheXianInfoData = data.zheXianInfo
        zheXianInfoData.forEach(item => {
          item.name = item.moneyTypeName
          item.type = 'line'
          item.symbolSize = 5
        })
        xAxisData.value = data.xaxisData
        zheXianInfo.value = zheXianInfoData
        initZheXian()

        const inpBillDetailVosThis = data.inpBillDetailVos;
        let transformedDataThis = [
          ['chargeType', 'charge']
        ]
        inpBillDetailVosThis.forEach(item => {
          transformedDataThis.push([
            item.classOnInpName,
            Number(item.charges).toFixed(2)
          ])
        })
        inpBillDetailVos.value = transformedDataThis
        initZhuYuanZhuZhuang()
        // 已诊人数
        totalInfo.value.alreadyPatient = data.alreadyPatient
        // 未诊人数
        totalInfo.value.pendingPatient = data.pendingPatient
        // 退号人数
        totalInfo.value.refundPatient = data.refundPatient
        // 科室未诊人数
        totalInfo.value.deptPendingPatient = data.deptPendingPatient
        // 科室已诊人数
        totalInfo.value.deptAlreadyPatient = data.deptAlreadyPatient
        // 科室退号人数
        totalInfo.value.deptRefundPatient = data.deptRefundPatient
        applyCountMap.value.examcount = data.applyCountMap.examcount
        applyCountMap.value.labcount = data.applyCountMap.labcount
        applyCountMap.value.prescriptioncount = data.applyCountMap.prescriptioncount
        applyCountMap.value.treatcount = data.applyCountMap.treatcount
        applyCountMap.value.noticecount = data.applyCountMap.noticecount
        applyCountMap.value.inflagok = data.applyCountMap.inflagok
        applyCountMap.value.inflagok = data.applyCountMap.inflagok
      } else {
        patientBarChartVos.value = [['category', '待诊', '已诊', '未诊', '退号']]
        initZhuZhuang()
        initZheXian()
        // 已诊人数
        totalInfo.value.alreadyPatient = 0
        // 未诊人数
        totalInfo.value.pendingPatient = 0
        // 退号人数
        totalInfo.value.refundPatient = 0
        // 科室未诊人数
        totalInfo.value.deptPendingPatient = 0
        // 科室已诊人数
        totalInfo.value.deptAlreadyPatient = 0
        // 科室退号人数
        totalInfo.value.deptRefundPatient = 0
      }
    })
  }
}

const getList = () => {
  let menuList: any[] = []
  /**
   * 获取快捷导航栏
   */
  getShortcutNavigation(userId.value).then(res => {
    if (res.data) {
      res.data.forEach(item => {
        const parentPathOne = !item.parentPathOne ? '' : item.parentPathOne
        let sysMenu = {
          title: item.menuName,
          children: [],
          icon: item.icon,
          // path: item.parentPath + "/" + item.path,
          path: parentPathOne + "/" + item.parentPath + "/" + item.path,
          // path: path.resolve(item.parentPath, item.path)
        }
        menuList.push(sysMenu)
      })
      fastMenu.value = menuList

    }
  })
}
/** 打开快捷导航栏 */
const shortcutNavigationClick = () => {
  shortcutNavigation.value.init()
}


function allSelect() {
  // 强制刷新所有数据和图表
  getList();
  getOutpatientRecordsListFun();
  getPatVisitList()
  getDoctorDataCollectFun();
}

onMounted(() => {
  // 1. 组件挂载时初始化：从 Pinia 状态读取已选中科室（处理路由刷新场景）
  // 如果用户已选择科室（如页面刷新后状态保留），直接加载数据
  if (useUserStore.user.currentSelectDept) {
    // 将全局状态中的科室 ID 同步到本地组件状态
    currentSelectDept.value = useUserStore.user.currentSelectDept
    // 执行数据加载逻辑（列表、图表等）
    allSelect()
  }
  // 2. 监听科室切换事件（处理用户主动切换科室场景）
  // 通过事件总线监听 Navbar 组件触发的科室切换事件
  eventBus.on('navbarDeptChange', (newDeptId: string) => {
    // 更新本地组件的科室 ID 状态
    currentSelectDept.value = newDeptId;
    // 执行数据加载逻辑（刷新列表、图表等）
    allSelect()
  });
});
// 组件卸载时移除监听（避免内存泄漏）
onUnmounted(() => {
  eventBus.off('navbarDeptChange');
});

</script>
<script lang="ts">


export default {
  name: "DashboardIndex"
}
</script>
<style lang="scss" scoped>

.home-page {
  width: 100%;
  height: 100%;
  display: flex;
  flex-wrap: wrap;

  .home-page-1, .home-page-2, .home-page-3 {
    border: 1px solid #eee;
    width: 33%;
    height: 170px;
  }

  .home-page-4, .home-page-5, .home-page-6 {
    border: 1px solid #eee;
    width: 33%;
    height: 300px;
    padding: 14px;
  }

  .home-page-7 {
    border: 1px solid #eee;
    width: 60%;
  }

  .home-page-8 {
    border: 1px solid #eee;
    width: 39%;
    height: calc(100% - 161px - 300px);
  }

  .home-page-1 {
    .user-info-welcome {
      padding: 10px;
      display: flex;
      background: #4E64F6;

      .user-pic {
        width: 60px;
        height: 60px;
        border-radius: 50%;
      }

      .user-text {
        margin: 20px 0 0 10px;

        .hello {
          font-size: 14px;
          color: #FFFFFF;
        }

        .weather {
          font-size: 12px;
          color: #DBE0FD;
        }
      }
    }

    .user-info-message {
      display: flex;
      justify-content: space-between;

      div {
        flex: 1;
        text-align: center;
        padding-top: 3px;

        p {
          margin: 0;
          padding: 0;
        }
      }

      .message-number {
        font-size: 31px;
        color: #333338;
      }

      .message-title {
        font-size: 14px;
        color: #98999B;
      }
    }
  }

  .home-page-2 {
    display: flex;
    flex-wrap: wrap;

    .tag-list-item {
      width: 25%;
      height: 50%;
      border: 1px solid #eee;
      display: flex;
      //justify-content: center;
      align-items: center;

      .tag-list-img {
        width: 45px;
        height: 45px;
        border-radius: 50%;
        margin-left: 15px;
        /* 添加以下属性实现文字居中 */
        display: flex;
        justify-content: center;
        align-items: center;
        color: white; /* 设置文字颜色为白色，与蓝色背景对比 */
        font-size: 13px; /* 适当调整字体大小 */
      }

      .tag-list-text {
        font-size: 14px;
        color: #333338;
        margin-left: 10px;
      }
    }
  }

  .home-page-3 {
    padding: 14px;

    .card-header {
      font-size: 14px;
      color: #333338;

      > :last-child {
        padding: 0;
        height: calc(100% - 40px);
      }

      // .list-item {
      //     // width: 84px;
      //     height: 32px;
      //     border-radius: 2px;
      //     border: 1px solid #4E64F6;
      // }

      // .card-row {
      //     display: flex;
      //     flex-wrap: wrap;
      //     .list-item {
      //         flex: 1;
      //     }
      // }
    }
  }

  .home-page-6-title {
    font-weight: 800;
    font-size: 18px;
    color: #333338;
  }

  .home-page-7 {
    .department-table {
      width: 100%;
      height: 100%;
      padding: 10px 20px 0 20px;
      background: #fff;
      // border-radius: 4px;
      // box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    }

    .custom-stripe-table {
      --el-table-tr-bg-color: #ffffff; /* 默认行颜色 */
      --el-table-row-striped-bg-color: red; /* 斑马纹行颜色 */
    }

    /* 鼠标悬停颜色 */
    .custom-stripe-table .el-table__body tr:hover > td {
      --el-table-tr-bg-color: red !important;
    }

    .el-table {
      height: calc(100% - 26px);
    }

    .el-progress {
      padding: 0 10px;
    }
  }

  .home-page-8 {

    .department-table {
      width: 100%;
      height: 100%;
      padding: 10px 20px 0 20px;
      background: #fff;
      // border-radius: 4px;
      // box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    }

    .custom-stripe-table {
      --el-table-tr-bg-color: #ffffff; /* 默认行颜色 */
      --el-table-row-striped-bg-color: red; /* 斑马纹行颜色 */
    }

    /* 鼠标悬停颜色 */
    .custom-stripe-table .el-table__body tr:hover > td {
      --el-table-tr-bg-color: red !important;
    }

    .el-table {
      height: calc(100% - 26px);
    }

    .el-progress {
      padding: 0 10px;
    }
  }

  :deep(.el-card__header) {
    padding: 0;
    border-bottom: none;
  }

  :deep(.el-card) {
    border: none;
    box-shadow: none;
  }

  // :deep(.el-card__body:nth-child(0)) {
  //     padding: 0 !important;
  // }
}

// :deep(.el-card__header) {
//     // margin-top: -15px !important;
//     // padding-bottom: 5px !important;
//     padding: 0;
//     border-bottom: none;
// }
:deep(.el-card__header) {
  padding: 0;
  border-bottom: none;
}

:deep(.el-calendar-table__row) {
  height: 145px;
}

.calendar-container {
  width: 620px;
  height: 400px;
}

.custom-calendar .el-calendar-day {
  height: 240px;

  p {
    margin-top: 0;
  }
}

.is-selected {
  color: #1989fa;
}

.card-wrap-class {
  flex: 1;
  text-align: center;
  border-radius: 4px;
  transition: all ease-in-out 0.3s;
  height: 100px;
  position: relative;
  background: #fff;
  cursor: pointer;

  nav {
    font-size: 15px;
    color: #333;
  }

  h2 {
    margin-top: 1px;
  }

  .card-wrap-class-content {
    display: flex;
    height: 100%;
    justify-content: center;
    align-items: center;

    > img {
      height: 60px;
      margin-right: 5px;
    }

    div {
      width: 90px;
    }
  }

  .card-wrap-class-footer {
    width: 100%;
    height: 30%;
    text-align: center;
    border-top: 1px solid #e5e5e5;
    color: #0353d6;

    :deep(.el-button) {
      font-size: 13px;
    }
  }
}

.home_header-no {
  position: relative;
  height: 100px;
  margin-bottom: 10px;
  border-radius: 4px;
  background: #fff;

  .img_left {
    position: absolute;
    left: 10px;
    top: 0;
    height: 100%;
  }

  .img_right {
    position: absolute;
    right: 0;
    top: 0;
    height: 100%;
  }

  > div {
    display: flex;
    flex-direction: column;
    justify-content: center;
    height: 100%;
    padding-left: 150px;

    > h2 {
      font-size: 20px;
      color: #0353d6;
    }
  }
}

.span {
  font-size: 15px;
  margin-left: 7px;
  position: absolute;
  margin-top: -17px;
  display: inline-block;
  max-width: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

:deep(.is-always-shadow) {
  height: 100%;
}

.svg-icon-nav {
  position: absolute;
  margin-top: -13px;
  margin-left: -12px;
}

</style>
